<?php

namespace app\admin\model\order;

use app\admin\model\goods\Goods;
use app\admin\model\goods\GoodsItem;
use app\admin\model\OrderRefund;
use app\admin\model\User;
use app\api\model\OrderSale;
use app\api\model\Usermoney;
use app\common\model\Detail;
use think\Db;
use think\Model;
use wxpay\Wechat;


class Order extends Model
{

    // 表名
    protected $name = 'order';
//    protected $resultSetType = 'collection';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'order_status_text',
        'pay_status_text',
        'pay_way_text',
        'pay_time_text',
        'shipping_status_text',
        'shipping_time_text',
        'confirm_take_time_text',
        'create_time_text',
        'update_time_text'
    ];



    public function getOrderStatusList()
    {
        return ['0' => __('Order_status 0'), '1' => __('Order_status 1'), '2' => __('Order_status 2'), '3' => __('Order_status 3'), '5' => __('Order_status 5'), '4' => __('Order_status 4'),'6' => __('Order_status 6')];
    }

    public function getPayStatusList()
    {
        return ['0' => __('Pay_status 0'), '1' => __('Pay_status 1'), '2' => __('Pay_status 2'), '3' => __('Pay_status 3')];
    }

    public function getPayWayList()
    {
        return ['0' => __('Pay_way 0'), '1' => __('Pay_way 1'), '2' => __('Pay_way 2')];
    }

    public function getShippingStatusList()
    {
        return ['0' => __('Shipping_status 0'), '1' => __('Shipping_status 1')];
    }

    public function getRefundStatusList()
    {
        return ['0' => __('Refund 0'), '1' => __('Refund 1'), '2' => __('Refund 2')];
    }


    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayWayTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_way']) ? $data['pay_way'] : '');
        $list = $this->getPayWayList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getShippingStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['shipping_status']) ? $data['shipping_status'] : '');
        $list = $this->getShippingStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getShippingTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['shipping_time']) ? $data['shipping_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getConfirmTakeTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['confirm_take_time']) ? $data['confirm_take_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setShippingTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setConfirmTakeTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function getShop($sid)
    {
        $shop_name = Db::name('user_shop')->where('id',$sid)->value('shop_name');
        if (empty($shop_name))
        {
            $shop_name = '店铺不存在|请核对';
        }
        return $shop_name;
    }

    public function getDeliverylist()
    {
       $response = Db::name('delivery_express')->where('is_delete',0)->select();
       return $response;
    }

    public function getcollocation($cid)
    {

        $res = Db::name('goods_collocation')
            ->alias('gc')
            ->join('goods g','g.id = gc.goods_id','LEFT')
            ->where('gc.id',$cid)
            ->value('g.name');

        return $res;
    }


    /**
     * @param $row  售后表
     * @param $orderData 退款信息
     * @param $orderGoods 订单商品信息
     */
    public function vip_refund($row,$orderData,$orderGoods)
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status' => false
        ];

        $time = time();

        Db::startTrans();
        try {
            if ($orderGoods['goods_num_price'] == $row['refund_price'])
            {

                OrderSale::where('id',$row['id'])->update(['status' => 6,'update_time' => $time]);
                $OrderRefundData = OrderRefund::where('refund_sn',$row['refund_sn'])->where('order_id',$row['order_goods_id'])->find();
                if ($OrderRefundData)
                {
                    OrderRefund::where('refund_sn',$row['refund_sn'])->where('order_id',$row['order_goods_id'])->update([
                        'refund_status' => 1,
                    ]);

                    OrderGoods::where('id',$row['order_goods_id'])->update([
                        'refund_status' => 3
                    ]);

                    $reder = OrderGoods::where('order_id',$row['order_id'])->where('refund_status',0)->find();
                    if (empty($reder))
                    {
                        Order::where('id',$row['order_id'])->update(['pay_status' => 2]);
                    }

                    if ($orderGoods['sku_id'] == 0)
                    {
                        Goods::where('id',$orderGoods['goods_id'])
                            ->setInc('stock',$orderGoods['goods_num']);
                    }else{
                        GoodsItem::where('id',$orderGoods['sku_id'])
                            ->setInc('stock',$orderGoods['goods_num']);
                    }

                    Usermoney::create([
                        'uid' => $orderData['uid'],
                        'money' => $row['refund_price'],
                        'type'  => 'refund', // 退款
                        'create_time' => $time,
                        'is_type' => 1
                    ]);
                    User::where('id',$orderData['uid'])->setInc('money',$row['refund_price']);
                    $result['status'] = true;
                    $result['msg'] = '退款成功';
                    Db::commit();
                }else{
                    $result['msg'] = '退款信息不存在请从新审核';
                }
            }else{
                $result['msg'] = '支付金额与退款金额不符';
            }

        }catch (\Exception $e)
        {
            var_dump($e->getMessage());
            Db::rollback();
            $result['msg'] = $e->getMessage();
        }

        return $result;
    }

    public function orderGoods()
    {
        return $this->hasMany('OrderGoods', 'order_id', 'id');
    }

    /**
     * 积分订单退款
     * @param $orderData 订单信息
     *
     */
    public function integral($orderData)
    {

        $result = [
            'data' => null,
            'msg'  => null,
            'status' => false
        ];
        $time = time();
        try {
            $orderData->order_status = 5;
            $orderData->pay_status   = 2;
            $orderData->update_time  = $time;
            $orderData->save();
            $orderId = $orderData->id;

            if(empty($orderId))
            {
                $result['msg'] = '订单关闭失败';
                Db::rollback();
            }else{


                $price = Db::name('order_goods')
                    ->where('order_id',$orderId)
                    ->where('refund_status',0)
                    ->sum('price');
                // 关闭商品订单
                Db::name('order_goods')
                    ->where('order_id',$orderId)
                    ->where('refund_status',0)
                    ->update(['refund_status' => 4]);
                $out_refund_no = order_sale_sn();
                $userModel = new User();
                $userRes = $userModel->userMoney($orderData['uid'],$price,'refund',1);

                if ($userRes == true)
                {
                    Db::name('order_refund')->insertGetId([
                        'uid' => $orderData['uid'],
                        'order_id' => $orderData['id'],
                        'refund_sn' => $out_refund_no,
                        'refund_price' => $orderData['pay_price'],
                        'refund_amount' => $price,
                        'refund_status' => 1,
                        'refund_way' => 0,
                        'refund_msg' => '积分退款',
                        'create_time' => $time,
                    ]);
                    Db::commit();
                    $result['status'] = true;
                    $result['msg'] = '操作成功';
                }else{
                    Db::rollback();
                    $result['msg'] = '操作失败';
                }
            }
        }catch(\Exception $e){
            var_dump($e->getMessage());
            Db::rollback();
            $result['msg'] = '关闭订单失败';
        }

        return $result;
    }

    /**
     * 微信退款
     */
    public function money($orderData)
    {

        $result = [
            'data' => null,
            'msg'  => null,
            'status' => false
        ];
        $time = time();
        $wechat = new Wechat();
        $out_refund_no = order_sale_sn();

        // 退款金额
        $price = Db::name('order_goods')
            ->where('order_id',$orderData['id'])
            ->where('refund_status',0)
            ->sum('price');

        $discounts = Db::name('order_goods')
            ->where('order_id',$orderData['id'])
            ->where('refund_status',0)
            ->sum('discounts');
        try{
            $orderRefund = $wechat->refunde($orderData['pay_sn'],$out_refund_no,$orderData['pay_price'],$price,'商家关闭交易');
            $orderRefund = json_decode($orderRefund, true);
            if ($orderRefund['return_code'] != 'SUCCESS' || $orderRefund['return_msg'] != 'OK' || $orderRefund['result_code'] != 'SUCCESS')
            {
                $result['msg'] = '退款失败';
            }else{
                // 修改订单状态
                $orderData->order_status = 5;
                $orderData->pay_status   = 2;
                $orderData->update_time  = $time;
                $orderData->save();
                $orderId = $orderData->id;

                if ($orderId)
                {
                    Db::name('order_goods')
                        ->where('order_id',$orderId)
                        ->where('refund_status',0)
                        ->update([
                            'refund_status' => 3
                        ]);
                    $refund_fee = $orderRefund['refund_fee'] * 0.01;
                    $orderRefundId = Db::name('order_refund')->insertGetId([
                        'uid'       => $orderData['uid'],
                        'order_id'  => $orderId,
                        'refund_sn' => $orderRefund['out_refund_no'],
                        'refund_price'  => $orderData['pay_price'],
                        'refund_amount' => $refund_fee,
                        'refund_status' => 1,
                        'refund_way'    => 0,
                        'wechat_refund_id'    => $orderRefund['refund_id'],
                        'refund_msg'    => $orderRefund['result_code'],
                        'create_time'   => $time,
                        'refund_integral' => $discounts
                    ]);

                    if ($orderRefundId)
                    {
                        // 返回积分
                        $userModel = new User();
                        // 退款积分
                        $integralRes = $userModel->userIntegral($orderData['uid'],$discounts,time(),'8','1');
                        if ($integralRes == true)
                        {
                            Detail::addPrice($orderData['uid'],2,$refund_fee,$time);
                            Db::commit();
                            $result['status'] = true;
                            $result['msg']    = '操作成功';
                        }else{
                            Db::rollback();
                            $result['msg']    = '退款操作失败3';
                        }
                    }else{
                        Db::rollback();
                        $result['msg']    = '退款操作失败4';
                    }
                }else{
                    Db::rollback();
                    $result['msg'] = '退款操作失败1';
                }
            }
        }catch (\Exception $e){
            Db::rollback();
            $result['msg'] = '关闭订单失败';
        }

        return $result;
    }

    /**
     * 关闭单个商品 金额
     */
    public function goodsMoney($id)
    {
        $result = [
            'data' => '',
            'msg'  => '',
            'status' => false
        ];
        $orderGoods = OrderGoods::get($id);
        $order = self::get($orderGoods['order_id']);
        $Wechat = new Wechat();
        $time = time();

        $out_refund_no = order_sale_sn();
        if ($orderGoods['price'] != 0)
        {

            $orderRefund = $Wechat->refunde($order['pay_sn'],$out_refund_no,$order['pay_price'],$orderGoods['price'],'关闭单个商品退款');
            $orderRefund = json_decode($orderRefund,true);
            if ($orderRefund['return_code'] != 'SUCCESS' || $orderRefund['return_msg'] != 'OK' || $orderRefund['result_code'] != 'SUCCESS')
            {
                $result['msg'] = '退款失败';
                return $result;
            }

        }

        try {
            //查找订单
            OrderGoods::where('id',$id)->update([
                'refund_status' => 3
            ]);
            $number = OrderGoods::where('order_id',$order['id'])
                ->where('refund_status',0)
                ->count();
            if ($number <= 0)
            {
                $order->order_status = 6;
                $order->pay_status   = 2;
                $order->update_time  = $time;
                $order->save();
            }

            Db::name('order_refund')->insertGetId([
                'uid' => $order['uid'],
                'order_id'  => $order['id'],
                'refund_sn' =>   empty($orderRefund['out_refund_no']) ? $out_refund_no : $orderRefund['out_refund_no'],
                'refund_price' => empty($orderRefund['total_fee']) ? $order['pay_price'] : $orderRefund['total_fee'] * 0.01,
                'refund_amount' => empty($orderRefund['refund_fee']) ? $orderGoods['price'] : $orderRefund['refund_fee'] * 0.01,
                'refund_status' => 1,
                'refund_way'    => 0,
                'wechat_refund_id' => empty($orderRefund['refund_id']) ? '' : $orderRefund['refund_id'],
                'refund_msg' => empty($orderRefund['result_code']) ? '' : $orderRefund['result_code'],
                'create_time' => $time,
                'refund_integral' => $orderGoods['discounts'],
                'order_goods' => $orderGoods['id'],
            ]);

            if ($orderGoods['price'] != 0)
            {
                Detail::addPrice($order['uid'],2,$orderGoods['price'],$time);
            }

            // 返回用户积分
            $userModel = new User();
            $userModel->userIntegral($order['uid'],$orderGoods['discounts'],$time,8,1);
            $result['status'] = true;
            $result['msg'] = '关闭成功';

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            echo $e->getMessage();
            $result['msg'] = '操作失败1';
        }
        return $result;
    }

    /**
     * 关闭商品 积分
     */
    public function goodsIntegral($id)
    {
        $result = [
            'data' => '',
            'msg'  => '',
            'status' => false
        ];
        $time = time();
        $orderGoods = OrderGoods::get($id);
        $out_refund_no = order_sale_sn();
        try {
            $orderGoods->refund_status = 3;
            $orderGoods->save();
            $order = Order::get($orderGoods['order_id']);
            $ordernum = OrderGoods::where('order_id',$order['id'])->where('refund_status',0)->count();
            if ($ordernum <= 0)
            {
                $order->order_status = 6;
                $order->pay_status   = 2;
                $order->update_time   = $time;
                $order->save();
            }

            OrderRefund::create([
                'uid' => $order['uid'],
                'order_id'  => $order['id'],
                'refund_sn' => $out_refund_no,
                'refund_price'  => $order['pay_price'],
                'refund_amount' => $orderGoods['price'],
                'refund_status' => 1,
                'refund_way'    => 0,
                'wechat_refund_id'    => 0,
                'create_time'    => $time,
                'order_goods'    => $orderGoods['id'],
            ]);

            $userModel = new User();
            $response = $userModel->userMoney($order['uid'],$orderGoods['price'],'refund',1);

            if ($response == true)
            {
                Db::commit();
                $result['msg']    = '关闭订单成功';
                $result['status'] = true;
            }else{
                Db::rollback();
                $result['msg']    = '关闭订单失败';
            }
        }catch(\Exception $e){
            echo $e->getMessage();
            Db::rollback();
            $result['msg'] = '关闭订单失败';
        }

        return $result;
    }

    public function userone()
    {
        return $this->belongsTo('app\admin\model\User','uid');
    }

    public function devileaddress()
    {
        return $this->belongsTo('app\admin\model\Delivaddress','deliv_address');
    }
}
